import { addUser, deleteUser, getUserList, updateUser } from '@/services/api/user';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Flex, Form, Popconfirm, Space, Switch } from 'antd';
import React, { useRef, useState } from 'react';

const menus: any = {
  1: '工作台',
  2: '分析页',
  3: '原始订单',
  4: '生产订单',
  5: '采购订单',
  6: '售后订单',
  7: '用户管理',
  8: '客户管理 ',
  9: '供应商管理',
  10: '日志管理',
  11: '登录日志管理',
};

const User: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [formEdit] = Form.useForm();
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [isShowCommission, setisShowCommission] = useState<boolean>(false);

  const columns: ProColumns[] = [
    {
      title: '头像',
      key: 'avator',
      dataIndex: 'avator',
      hideInSearch: true,
      render: (_, record) => {
        return <img style={{ width: '30px', height: '30px' }} src={record.avatar} alt="" />;
      },
    },
    {
      title: '用户名',
      key: 'nickname',
      dataIndex: 'nickname',
      copyable: true,
    },
    {
      title: '账户名',
      key: 'username',
      dataIndex: 'username',
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '手机号',
      key: 'phone',
      dataIndex: 'phone',
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '职位',
      key: 'position',
      dataIndex: 'position',
      valueType: 'select',
      valueEnum: {
        1: '设计师',
        2: '销售',
        3: '其他',
      },
    },
    {
      title: '菜单权限',
      key: 'menus',
      dataIndex: 'menus',
      valueType: 'select',
      hideInSearch: true,
      valueEnum: menus,
      fieldProps: {
        mode: 'multiple',
      },
      width: 300,
      render: (_, record) => {
        let node: any = [];
        if (record.menus !== '' && record.menus !== null) {
          Object.keys(menus).forEach((el) => {
            if (record?.menus?.indexOf(el) !== -1) {
              node.push(
                <span
                  style={{
                    color: '#1e80ff',
                    fontSize: '12px',
                    minWidth: '40px',
                    textAlign: 'left',
                  }}
                >
                  {menus[el]}
                </span>,
              );
            }
          });
        }

        return (
          <Flex gap="4px 4px" wrap>
            {node}
          </Flex>
        );
      },
    },
    // {
    //   title: '销售提成',
    //   key: 'commission',
    //   dataIndex: 'commission',
    //   hideInSearch: true,
    //   render: (text, record) => {
    //     let node = <></>;
    //     if (record.position === '2') {
    //       node = <Tag color="green">{text}%</Tag>;
    //     }
    //     return node;
    //   },
    // },
    // {
    //   title: '权限',
    //   dataIndex: 'access',
    //   hideInSearch: true,
    //   key: 'status',
    //   valueType: 'select',
    //   valueEnum: {
    //     boss: '老板',
    //     user: '员工',
    //     admin: '管理员',
    //   },
    // },
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      key: 'status',
      valueEnum: {
        0: '已离职',
        1: '在职',
      },
      valueType: 'select',
      render: (_, record) => {
        return <>{record.status === '1' ? '在职' : '已离职'}</>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      key: 'status',
      valueEnum: {
        0: '已离职',
        1: '在职',
      },
      valueType: 'select',
      render: (_, record) => {
        return (
          <>
            <Popconfirm
              key="update"
              title="修改状态"
              description="确定要修改状态吗?"
              onConfirm={async () => {
                const success = await updateUser({
                  id: record.id,
                  status: record.status === '0' ? '1' : '0',
                });
                if (success?.code === 200) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
              // onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <Switch
                checked={record.status === '1'}
                checkedChildren="在职"
                unCheckedChildren="已离职"
              />
            </Popconfirm>
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      key: 'option',
      valueType: 'option',
      render: (_, record: any) => {
        return (
          <Space>
            <a
              key="edit"
              onClick={() => {
                setisShowCommission(record.position === '2');
                handleUpdateModalOpen(true);
                formEdit.setFieldsValue({
                  ...record,
                  postion: record.position.toString(),
                  menus: record.menus.length ? record.menus.split(',') : [],
                });
                setCurrentId(record.id);
              }}
            >
              修改
            </a>
            <Popconfirm
              key="delete"
              title="删除"
              description="确定要删除该用户吗?"
              onConfirm={async () => {
                const success = await deleteUser(record.id);
                if (success?.code === 200) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
              // onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <a style={{ color: 'red' }}>删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        pagination={{
          showSizeChanger: true,
        }}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setisShowCommission(false);
              handleModalOpen(true);
              form.resetFields();
            }}
          >
            <PlusOutlined /> 新增
          </Button>,
        ]}
        request={getUserList}
        columns={columns}
        rowSelection={false}
      />
      <ModalForm
        title={'新增用户'}
        modalProps={{
          destroyOnClose: true,
        }}
        form={form}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await addUser({ ...value, menus: value.menus.join(',') });
          if (success?.code === 200) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="nickname"
        />

        <ProFormText
          label="账号"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="username"
        />

        <ProFormText.Password
          label="密码"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          fieldProps={{
            autoComplete: 'new-password',
          }}
          name="password"
        />

        <ProFormText
          label="手机号"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="phone"
        />
        {/* <ProFormSelect
          showSearch
          label="权限"
          rules={[
            {
              required: true,
              message: '请选择权限',
            },
          ]}
          valueEnum={{
            user: { text: '员工', status: 'user' },
            admin: { text: '管理员', status: 'admin' },
            boss: { text: '老板', status: 'boss' },
          }}
          name="access"
        /> */}
        <ProFormSelect
          showSearch
          label="菜单权限"
          rules={[
            {
              required: true,
              message: '请选择权限',
            },
          ]}
          mode="multiple"
          valueEnum={menus}
          name="menus"
        />
        <ProFormSelect
          showSearch
          label="职位"
          rules={[
            {
              required: true,
              message: '请选择职位',
            },
          ]}
          onChange={(val) => {
            if (val === '2') {
              setisShowCommission(true);
            } else {
              setisShowCommission(false);
            }
          }}
          valueEnum={{
            '1': '设计师',
            '2': '销售',
            '3': '其他',
          }}
          name="position"
        />
        {isShowCommission && (
          <ProFormText
            label="销售提成(%)"
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}
            name="commission"
          />
        )}
      </ModalForm>

      <ModalForm
        title={'修改用户'}
        form={formEdit}
        modalProps={{
          destroyOnClose: true,
        }}
        open={updateModalOpen}
        onOpenChange={handleUpdateModalOpen}
        onFinish={async (value) => {
          const success = await updateUser({
            ...value,
            id: currentId,
            menus: value.menus.join(','),
          });
          if (success?.code === 200) {
            handleUpdateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="用户名"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="nickname"
        />

        <ProFormText
          label="账号"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="username"
        />

        <ProFormText
          label="手机号"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="phone"
        />
        <ProFormSelect
          showSearch
          label="菜单权限"
          rules={[
            {
              required: true,
              message: '请选择权限',
            },
          ]}
          mode="multiple"
          valueEnum={menus}
          name="menus"
        />
        {/* <ProFormSelect
          showSearch
          label="权限"
          rules={[
            {
              required: true,
              message: '请选择权限',
            },
          ]}
          valueEnum={{
            user: { text: '员工', status: 'user' },
            admin: { text: '管理员', status: 'admin' },
            boss: { text: '老板', status: 'boss' },
          }}
          onChange={(val) => {
            if (val === '2') {
              setisShowCommission(true);
            } else {
              setisShowCommission(false);
            }
          }}
          name="access"
        /> */}
        <ProFormSelect
          disabled
          showSearch
          label="职位"
          rules={[
            {
              required: true,
              message: '请选择职位',
            },
          ]}
          valueEnum={{
            '1': '设计师',
            '2': '销售',
            '3': '其他',
          }}
          onChange={(val) => {
            if (val === '2') {
              setisShowCommission(true);
            } else {
              setisShowCommission(false);
            }
          }}
          name="position"
        />
        {isShowCommission && (
          <ProFormText
            label="销售提成(%)"
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}
            name="commission"
          />
        )}
      </ModalForm>
    </PageContainer>
  );
};

export default User;
